<template>
	<div class="device-info-list-container">
		<Row>
			<Col span="4">
			<Tree :data="areaList" class="tree-data-container" @on-select-change="onSelectChange" />
			</Col>
			<Col span="20">
			<Button type="error" icon="md-add" @click="onAdd" :disabled="selectedArea.nodeLevel !== 4">新增设备</Button>
			<div class="ivu-inline-block ivu-fr">
				<Dropdown @on-click="onChangeTableSize" trigger="click">
					<Tooltip class="ivu-ml" content="密度" placement="top">
						<i-link>
							<Icon type="md-list" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
							<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
							<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
						</DropdownMenu>
					</template>
				</Dropdown>
				<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
					<i-link @click="onFullscreen">
						<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
					</i-link>
				</Tooltip>
				<Tooltip class="ivu-ml" content="刷新" placement="top">
					<i-link @click="onRefresh">
						<Icon custom="i-icon i-icon-refresh" />
					</i-link>
				</Tooltip>
				<Dropdown trigger="click">
					<Tooltip class="ivu-ml" content="列设置" placement="top">
						<i-link>
							<Icon type="md-options" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<div class="ivu-p-8">列展示</div>
							<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
							<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
								@click="item.show = !item.show">
								<Checkbox v-model="item.show"></Checkbox>
								<span>{{ item.title }}</span>
							</li>
						</DropdownMenu>
					</template>
				</Dropdown>
			</div>
			<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt">
				<template #deviceName="{ row }">
					<a style="color: #2d8cf0;" @click="onShowSignal(row)">{{ row.deviceName }}</a>
				</template>
				<template #action="{ row }">
					<div @click.stop.prevent>
						<a style="color: #2d8cf0;" @click="onShowEdit(row)">编辑</a>
						<Divider type="vertical" />
						<Poptip confirm title="您确定删除该设备了吗？" transfer @on-ok="onDelete(row)">
							<a style="color: #ed4014;">删除</a>
						</Poptip>
					</div>
				</template>
			</Table>
			<div class="ivu-mt ivu-text-center">
				<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
					@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
			</div>
			</Col>
		</Row>
		<Modal title="新增设备" v-model="visible" @on-cancel="onCancel" class-name="form-modal" :mask-closable="false"
			:width="1000">
			<Row :gutter="8">
				<Col span="11">
				<Table size="small" :columns="deviceColumns" :data="filteredAllDevices"
					@on-selection-change="onCheckDeviceChange" />
				</Col>
				<Col span="2">
				<div class="arrow">
					<Icon type="md-arrow-round-forward" size="24" @click="onConfirmSelect" />
					<Icon type="md-arrow-round-back" size="24" style="margin-top: 10px;" @click="onCancelSelect" />
				</div>
				</Col>
				<Col span="11">
				<Table size="small" :columns="selectedDeviceColumns" :data="selectedDevices"
					@on-selection-change="onCheckDeviceChange">
					<template #deviceCategory="{ row }">
						<Select transfer @on-change="val => onChangeCategory(val, row)">
							<Option key="0" :value="0">
								<span>末端制冷</span>
							</Option>
							<Option key="1" :value="1">
								<span>环境</span>
							</Option>
						</Select>
					</template>
					<template #deviceType="{ row }">
						<Select transfer @on-change="val => onChangeType(val, row)">
							<Option key="0" :value="0">
								<span>机房环境</span>
							</Option>
							<Option key="1" :value="1">
								<span>精密空调</span>
							</Option>
							<Option key="2" :value="2">
								<span>普通空调</span>
							</Option>
						</Select>
					</template>
				</Table>
				</Col>
			</Row>
			<template #footer>
				<Button type="text" @click="onCancel">取消</Button>
				<Button type="primary" @click="onConfirm" :loading="loading">确定</Button>
			</template>
		</Modal>
		<Modal title="编辑设备" v-model="editVisible" @on-cancel="onCancelEdit" class-name="form-modal" :mask-closable="false"
			:width="600">
			<Form ref="deviceInfo" :model="deviceInfo" :rules="deviceRules">
				<Row :gutter="16">
					<Col span="24">
					<FormItem label="设备名称" prop="deviceName">
						<Input v-model="deviceInfo.deviceName" placeholder="请输入设备名称" />
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="设备种类">
						<Select v-model="deviceInfo.deviceCategory" placeholder="请选择设备种类">
							<Option key="0" value="0">
								<span>末端制冷</span>
							</Option>
							<Option key="1" value="1">
								<span>环境</span>
							</Option>
						</Select>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="设备类型">
						<Select v-model="deviceInfo.deviceType" placeholder="请选择设备类型">
							<Option key="0" value="0">
								<span>机房环境</span>
							</Option>
							<Option key="1" value="1">
								<span>精密空调</span>
							</Option>
							<Option key="2" value="2">
								<span>普通空调</span>
							</Option>
						</Select>
					</FormItem>
					</Col>
				</Row>
			</Form>
			<template #footer>
				<Button type="text" @click="onCancelEdit">取消</Button>
				<Button type="primary" @click="onConfirmEdit" :loading="loading">确定</Button>
			</template>
		</Modal>
		<Modal title="设备信号" v-model="signalVisible" @on-cancel="onCancelSignal" :mask-closable="false" :width="1000">
			<Table ref="table" :columns="signalColumns" :data="signalList" size="small" class="ivu-mt">
				<template #action="{ row }">
					<div @click.stop.prevent>
						<a style="color: #2d8cf0;" v-if="['DO', 'AO'].includes(row.signalType)">调控</a>
						<a style="color: #c5c8ce; cursor: not-allowed;" v-else>调控</a>
						<Divider type="vertical" />
						<Poptip confirm title="您确定删除吗？" transfer @on-ok="onDeleteSignal(row)">
							<a style="color: #ed4014;">删除</a>
						</Poptip>
					</div>
				</template>
			</Table>
			<template #footer>
				<Button type="primary" @click="onCancelSignal">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import { resolveComponent } from 'vue'
import DayJs from 'dayjs'
import { cloneDeep } from 'lodash'
import { getAreaList } from '@/api/common'
import {
	getDeviceInfoList,
	getResDeviceList,
	createDeviceInfo,
	updateDeviceInfo,
	getSignalList,
	deleteSignal,
	getSignalDataList
} from '@api/device-info'
import LineData from './line-data.vue';

export default {
	data() {
		return {
			loading: false,
			list: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			allDevices: [],
			visible: false,
			areaData: [],
			areaList: [],
			selectedArea: {},
			selectingDevices: [],
			selectedDevices: [],
			editVisible: false,
			deviceInfo: {
				id: '',
				deviceName: '',
				deviceCategory: '',
				deviceType: ''
			},
			deviceRules: [{
				deviceName: [
					{ required: true, message: '请输入设备名称' }
				]
			}],
			currentRow: {},
			signalVisible: false,
			signalList: [],
			collectList: []
		}
	},
	computed: {
		columns() {
			return [
				{ title: '设备名称', key: 'deviceName', slot: 'deviceName' },
				{ title: '设备种类', key: 'deviceCategoryName' },
				{ title: '设备类型', key: 'deviceTypeName' },
				{ title: '所属机房', key: 'roomName' },
				{ title: '所属局站', key: 'regionName' },
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 120, fixed: 'right' }
			]
		},
		tableColumns() {
			const columns = [...this.columns];
			return columns
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		},
		deviceColumns() {
			return [
				{ type: 'selection', align: 'center', width: 60 },
				{ title: '设备名称', key: 'deviceName' },
				{ title: '节点类型', key: 'nodeName' },
				{ title: '所属产品', key: 'productName' },
			]
		},
		selectedDeviceColumns() {
			return [
				{ type: 'selection', align: 'center', width: 60 },
				{ title: '设备名称', key: 'deviceName' },
				{ title: '设备种类', key: 'deviceCategory', slot: 'deviceCategory' },
				{ title: '设备类型', key: 'deviceType', slot: 'deviceType' },
			]
		},
		filteredAllDevices() {
			return this.allDevices.filter(item => {
				return !this.selectedDevices.map(i => i.id).includes(item.id)
			})
		},
		signalColumns() {
			return [
				{
					type: 'expand',
					width: 1,
					render: (h, { row }) => {
						return h('div', [
							h('span', '开始时间：'),
							h(resolveComponent('DatePicker'), {
								placeholder: '开始日期',
								style: {
									width: '200px',
									marginRight: '5px'
								},
								modelValue: row.startDate,
								'onOn-change': (startDate) => {
									const found = this.signalList.find(
										item => item.deviceSignalId === row.deviceSignalId
									)
									found.startDate = startDate
								}
							}),
							h(resolveComponent('TimePicker'), {
								placeholder: '开始时间',
								confirm: true,
								style: {
									width: '100px',
									marginRight: '15px'
								},
								modelValue: row.startTime,
								'onOn-change': (startTime) => {
									const found = this.signalList.find(
										item => item.deviceSignalId === row.deviceSignalId
									)
									found.startTime = startTime
								}
							}),
							h('span', '结束时间：'),
							h(resolveComponent('DatePicker'), {
								placeholder: '结束日期',
								style: {
									width: '200px',
									marginRight: '5px'
								},
								modelValue: row.endDate,
								'onOn-change': (endDate) => {
									const found = this.signalList.find(
										item => item.deviceSignalId === row.deviceSignalId
									)
									found.endDate = endDate
								}
							}),
							h(resolveComponent('TimePicker'), {
								placeholder: '结束时间',
								confirm: true,
								style: {
									width: '100px',
								},
								modelValue: row.endTime,
								'onOn-change': (endTime) => {
									const found = this.signalList.find(
										item => item.deviceSignalId === row.deviceSignalId
									)
									found.endTime = endTime
								}
							}),
							h(resolveComponent('Button'), {
								type: 'primary',
								confirm: true,
								style: {
									marginLeft: '10px'
								},
								onClick: async () => {
									const response = await getSignalDataList({
										deviceId: this.currentRow.id,
										signalId: row.signalId,
										startDate: `${row.startDate} ${row.startTime}`,
										endDate: `${row.endDate} ${row.endTime}`
									})
									this.collectList = response.map(item => ({
										collectTime: item.collectTime,
										collectValue: item.collectValue
									}))
								}
							}, ['查询']),
							h(LineData, {
								lineData: this.collectList
							})
						])
					}
				},
				{ title: '信号名称', key: 'signalName' },
				{ title: '网关来源', key: 'productName' },
				{ title: '信号类型', key: 'signalType' },
				{ title: '当前参数', key: 'collectValue' },
				{ title: '单位', key: 'unit' },
				{
					title: '趋势图',
					key: 'line',
					align: 'center',
					render: (h, { row }) => {
						return h('div', [
							h(resolveComponent('Icon'), {
								type: 'ios-podium',
								size: 20,
								color: '#2d8cf0',
								style: { cursor: 'pointer' },
								onClick: async () => {
									const response = await getSignalDataList({
										deviceId: this.currentRow.id,
										signalId: row.signalId,
										startDate: `${row.startDate} ${row.startTime}`,
										endDate: `${row.endDate} ${row.endTime}`
									})
									this.collectList = response.map(item => ({
										collectTime: item.collectTime,
										collectValue: item.collectValue
									}))
									this.signalList.forEach(item => {
										if (item.deviceSignalId !== row.deviceSignalId) {
											item._expanded = false
										} else {
											item._expanded = !item._expanded
										}
									})
								}
							}),
						]);
					}
				},
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 120 }
			]
		}
	},
	async mounted() {
		const response = await getAreaList({})
		this.areaData = response
		this.onGenerateTree(response)
	},
	methods: {
		async getAllDevices() {
			const response = await getResDeviceList({
				pageNum: 1,
				pageSize: 1000,
			})
			this.allDevices = (response || []).map(item => ({
				...item,
				nodeName: ({
					1: '网关设备',
					0: '网关子设备'
				})[item.nodetype]
			}))
		},
		async getData() {
			if (this.loading) return;
			this.loading = true;
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getDeviceInfoList({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				deviceName: params.deviceName || undefined
			})
			this.list = (response.records || []).map(item => ({
				...item,
				deviceCategoryName: ({
					1: '环境',
					0: '末端制冷'
				})[item.deviceCategory],
				deviceTypeName: ({
					0: '机房环境',
					1: '精密空调',
					2: '普通空调'
				})[item.deviceType],
			}))
			this.total = response.total;
			this.loading = false;
		},
		onGenerateTree(areaList) {
			const treeData = areaList.filter(area => !area.parentId)
			for (let i = 0; i < treeData.length; i++) {
				treeData[i].expand = true
				treeData[i].children = []
				treeData[i].render = (h, { root, node, data }) => {
					return h('span', {}, data.nodeName)
				}
				cloneDeep(areaList).forEach(area => {
					if (area.parentId === treeData[i].nodeId) {
						if (!area.children) {
							area.expand = true
							area.children = []
							cloneDeep(areaList).forEach(subArea => {
								if (subArea.parentId === area.nodeId) {
									subArea.expand = true
									subArea.children = []
									cloneDeep(areaList).forEach(thirdArea => {
										if (thirdArea.parentId === subArea.id) {
											thirdArea.expand = true
											thirdArea.children = []
											thirdArea.render = (h, { root, node, data }) => {
												return h('span', {
													style: {
														width: '100%'
													}
												}, [
													h('span', {
														style: {
															display: 'inline-block',
															width: '80px',
														}
													}, data.nodeName),
												]);
											}
											subArea.children.push(thirdArea)
										}
									})
									subArea.render = (h, { root, node, data }) => {
										return h('span', {
											style: {
												width: '100%'
											}
										}, [
											h('span', {
												style: {
													display: 'inline-block',
													width: '80px',
												}
											}, data.nodeName),
										]);
									}
									area.children.push(subArea)
								}
							})
						}
						area.render = (h, { root, node, data }) => {
							return h('span', {
								style: {
									width: '100%'
								}
							}, [
								h('span', {
									style: {
										display: 'inline-block',
										width: '80px',
									}
								}, data.nodeName),
							]);
						}
						areaList[i].children.push(area)
					}
				})
			}
			this.areaList = treeData
		},
		onSelectChange(_, selectedArea) {
			this.selectedArea = selectedArea
			this.getData()
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		onAdd() {
			this.getAllDevices()
			this.visible = true
		},
		onCheckDeviceChange(selection) {
			this.selectingDevices = selection.map(item => ({
				...item,
				deviceType: '',
				deviceCategory: ''
			}))
		},
		onConfirmSelect() {
			this.selectedDevices = [
				...this.selectedDevices,
				...this.selectingDevices
			]
			this.selectingDevices = []
		},
		onCancelSelect() {
			this.selectedDevices = this.selectedDevices.filter(item => {
				return !this.selectingDevices.map(i => i.id).includes(item.id)
			})
			this.selectingDevices = []
		},
		onChangeCategory(val, row) {
			this.selectedDevices.find(item => item.id === row.id).deviceCategory = val
		},
		onChangeType(val, row) {
			this.selectedDevices.find(item => item.id === row.id).deviceType = val
		},
		onCancel() {
			this.selectedDevices = []
			this.selectingDevices = []
			this.visible = false
		},
		async onConfirm() {
			const parent = this.areaData.find(item => {
				return item.id === this.selectedArea.parentId
			}) || {}
			const params = this.selectedDevices.map(item => {
				return {
					roomId: parent.id,
					roomName: parent.nodeName,
					regionId: this.selectedArea.id,
					regionName: this.selectedArea.nodeName,
					deviceName: item.deviceName,
					deviceCode: item.deviceCode,
					deviceType: item.deviceType,
					deviceCategory: item.deviceCategory
				}
			})
			const response = await createDeviceInfo(params)
			if (response.code === 1000) {
				this.onCancel()
				this.onSearch()
			}
		},
		async onDelete(row) {
			const response = await updateDeviceInfo({
				id: row.id,
				isDelete: 1
			})
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		},
		onShowEdit(row) {
			this.editVisible = true
			this.deviceInfo = { ...row }
		},
		onCancelEdit() {
			this.editVisible = false
			this.deviceInfo = {
				id: '',
				deviceName: '',
				deviceCategory: '',
				deviceType: ''
			}
		},
		async onConfirmEdit() {
			const response = await updateDeviceInfo({
				...this.deviceInfo
			})
			if (response.code === 1000) {
				this.$Message.success('编辑成功')
				this.getData()
				this.onCancelEdit()
			}
		},
		onShowSignal(row) {
			this.currentRow = row
			this.signalVisible = true
			this.onGetSignalList()
		},
		async onGetSignalList() {
			const response = await getSignalList({
				deviceId: this.currentRow.id
			})
			this.signalList = response.map(item => ({
				...item,
				startDate: DayJs().format('YYYY-MM-DD'),
				startTime: '00:00:00',
				endDate: DayJs().format('YYYY-MM-DD'),
				endTime: '23:59:59'
			}))
		},
		onCancelSignal() {
			this.currentRow = {}
			this.signalVisible = false
		},
		async onDeleteSignal(row) {
			const response = await deleteSignal({
				deviceId: this.currentRow.id,
				signalId: row.signalId,
				isDelete: 1
			});

			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.onGetSignalList()
			}
		}
	}
}
</script>
<style lang="less">
.form-modal {
	.ivu-form-item-label {
		width: 100%;
		text-align: left;
	}

	.ivu-date-picker {
		width: 100%;
	}

	.arrow {
		width: 100%;
		height: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
}
</style>
